﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Rotempco.BaseClass.Objects.AttributeStoreObjects;

namespace Rotempco.BaseClass.Logic
{
    public class PasswordLogic
    {

        public static bool IsValidPassword(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
                return false;

            PasswordSetting passwordSettings = Factory.PasswordSetting.GetPasswordSettings();

            if (password.Length < passwordSettings.MinimumPasswordLength.Value)
                return false;

            if (passwordSettings.PasswordMustContainCapitalLetter)
            {
                if (password.ToLower().Equals(password))
                    return false;
            }

            if (passwordSettings.PasswordMustContainDigit)
            {
                if (!Regex.IsMatch(password, @"\d"))
                    return false;
            }

            return true;
        }

        public static string GetRandomPassword(int passwordLength)
        {
            //Removed O, o, 0, l, 1 
            string allowedLetterChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
            string allowedNumberChars = "23456789";
            char[] chars = new char[passwordLength];
            Random random = new Random();

            bool useLetter = true;
            for (int i = 0; i < passwordLength; i++)
            {
                if (useLetter)
                {
                    chars[i] = allowedLetterChars[random.Next(0, allowedLetterChars.Length)];
                    useLetter = false;
                }
                else
                {
                    chars[i] = allowedNumberChars[random.Next(0, allowedNumberChars.Length)];
                    useLetter = true;
                }
            }

            return new string(chars);
        }

        public static string GetRandomPassword()
        {
            PasswordSetting passwordSettings = Factory.PasswordSetting.GetPasswordSettings();
            int passwordLength = passwordSettings.MinimumPasswordLength.Value;
            return GetRandomPassword(passwordLength);
        }
    }
}
